//
//  XJTixianViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/24.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJTixianViewController.h"
#import "XJWalletTiXianAccountViewController.h"


#import "XJTiXianAmountCell.h" //提现金额cell
#import "XJTiXianSectionHeaderView.h" // 区头
#import "XJAddTiXianAccountCell.h" // 点击添加提现账户cell
#import "XJTixianCell.h"

//model
#import "XJTiXianModel.h"
#import "XJWalletTiXianBankModel.h" // 这个是调 “确认提现接口用的”



@interface XJTixianViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) NSMutableArray *sectionArr;
@property (nonatomic, strong) NSMutableArray *accountArr; // 提现账户数
/**确认提现接口用的*/
@property (nonatomic, strong) NSMutableArray * tiXianArray;

@property(nonatomic, strong) UIView *tvFooterView;

/**629 账户余额*/
@property (nonatomic, copy) NSString *balance;
/**1.标记请求提现金额*/
@property (nonatomic, copy) NSString *tiXianMoney;
/**2.标记是否选择了提现账户 indexPath.row+1 。用的时候再-1*/
@property (nonatomic, assign) NSInteger index;



@end

@implementation XJTixianViewController

#pragma mark - 一  lazy
- (NSMutableArray *)accountArr {
    if (!_accountArr) {
        _accountArr = [NSMutableArray array];
    }
    return _accountArr;
}


- (NSMutableArray *)tiXianArray {
    if (!_tiXianArray) {
        _tiXianArray = [NSMutableArray array];
    }
    return _tiXianArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        // 注册cell
        [_tableView registerNib:[UINib nibWithNibName:@"XJTiXianAmountCell" bundle:nil] forCellReuseIdentifier:@"XJTiXianAmountCell"];
        
        [_tableView registerClass:[XJTiXianSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"XJTiXianSectionHeaderView"];
        [_tableView registerNib:[UINib nibWithNibName:@"XJAddTiXianAccountCell" bundle:nil] forCellReuseIdentifier:@"XJAddTiXianAccountCell"];
        
        [_tableView registerNib:[UINib nibWithNibName:@"XJTixianCell" bundle:nil] forCellReuseIdentifier:@"XJTixianCell"];
        
    }
    return _tableView;
}

- (UIView *)tvFooterView {
    if (!_tvFooterView) {
        _tvFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 100)];
        
        // 确定按钮
        UIButton *sureButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [sureButton setTitle:@"确认提现" forState:(UIControlStateNormal)];
        [sureButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [sureButton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateHighlighted)];

        sureButton.backgroundColor = XJCOLOR_RGB(255, 218, 67);
        sureButton.layer.masksToBounds = YES;
        sureButton.layer.cornerRadius = 10;
        sureButton.frame = CGRectMake(15, 30, KWidth - 30, 40);
        
        [sureButton addTarget:self action:@selector(sureButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [_tvFooterView addSubview:sureButton];
        
        
    }
    return _tvFooterView;
}
#pragma mark - 一 -1 确认提现
- (void)sureButtonAction:(UIButton *)button {
    
    XJLog(@"确认提现");
    
    NSString * yuE = self.balance;
    NSString * tiXianMoney = self.tiXianMoney ;
    
    if ([NSString isEmptyString:yuE]) {
        [JRToast showWithText:@"未来巴扎:账户余额不足"];
        return;
    }
    // 判断:提现账户不能<0,必须选择提现账户
    if ([NSString isEqual:tiXianMoney]) {
        [JRToast showWithText:@"未来巴扎:请输入提现金额"];
        return;
    }
    
    if ([yuE integerValue] < [tiXianMoney integerValue]) {
        [JRToast showWithText:@"未来巴扎:提现金额不能操作账户余额"];
        return;
    }
    
    if (self.index < 1) { //没有选择账户余额
        [JRToast showWithText:@"未来巴扎:请选择提现账户"];
        return;
    }
    
    
    XJLog(@"组装请求参数");
    //0 取出的是银行 1取出的是支付宝
    
    XJLog(@"%@",self.tiXianArray[self.index - 1]);
    if ([self.tiXianArray[self.index -1] isKindOfClass:[XJWalletTiXianZFBModel class]]) {
        XJLog(@"支付宝model");
        XJWalletTiXianZFBModel *zfbM = self.tiXianArray[self.index - 1];
        
        NSDictionary *zfbDic = @{@"type":@"0",
                                 @"real_money":tiXianMoney,
                                 @"pay_name":zfbM.pay_name,
                                 @"customer_name":zfbM.customer_name
                                 };
        
        [self requestTiXianWithDic:zfbDic];
        
    }else {
        XJLog(@"银行卡model");
        XJWalletTiXianBankModel *bankM = self.tiXianArray[self.index - 1];
        NSDictionary *zfbDic = @{@"type":@"1",
                                 @"real_money":tiXianMoney,
                                 @"card_name":bankM.card_name,
                                 @"bank_branch":bankM.bank_branch,
                                 @"bank_name":bankM.bank_name,
                                 @"card_number":bankM.card_number
                                 };
        
        [self requestTiXianWithDic:zfbDic];
    }

    //银行卡提现请求参数:对应不同的model
    
    //支付宝提现请求参数:对应不同的model
    
    //调接口
}

#pragma mark - 二  生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navTitle = @"提现";
    [self setupView];
    
    [self moniData];
    
    [self requestData];
    
    self.index = 0; //默认没有选中提现账户
    
}


- (void)moniData {
    self.sectionArr = @[@"请输入提现金额",@"请选择提现账户"].mutableCopy;
}
- (void)setupView {
    self.tableView.frame = CGRectMake(0, 0, KWidth, KHeight-XJTopNavH);
    
    [self.view addSubview:self.tableView];
    
    //表尾
    self.tableView.tableFooterView = self.tvFooterView;
}

#pragma mark - 三 UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0 ){
        return 1;
    }else {
        if (self.accountArr.count) { // 如果有数据就显示
            return self.accountArr.count;
        }else { //如果没有数据就显示 点击添加提现账户
            return 1;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        XJTiXianAmountCell *tixianCell = [tableView dequeueReusableCellWithIdentifier:@"XJTiXianAmountCell"];
        
        [tixianCell tixianCellPlaceholder:self.balance text:@""];
        
        XJWeakSelf(tixianCell)
        tixianCell.clickAllTiXianButtonBlock = ^{
            XJLog(@"点击全部提现");
            [weaktixianCell tixianCellPlaceholder:self.balance text:self.balance];
            
            XJLog(@"提现金额是:%@",self.balance);
            
            self.tiXianMoney = self.balance;
        };
        
        tixianCell.moneyTextFieldBlock = ^(NSString *money) {
            XJLog(@"提现金额是:%@",money);
            self.tiXianMoney = money;
        };
        
        return tixianCell;
    }else {
        // 判断rowArr是否有数据
        if (self.accountArr.count) { // 显示对应的cell
            
            XJTixianCell *tiXianCell = [tableView dequeueReusableCellWithIdentifier:@"XJTixianCell"];
            tiXianCell.selectionStyle = UITableViewCellSelectionStyleNone;
            tiXianCell.model = self.accountArr[indexPath.row];
            
            return tiXianCell;
        }else { // 显示点击添加提现cell
            
            XJAddTiXianAccountCell *addTixianAccountCell = [tableView dequeueReusableCellWithIdentifier:@"XJAddTiXianAccountCell"];
            return addTixianAccountCell;
        }
    }
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 80;
    }else {
        return 44;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    XJTiXianSectionHeaderView *sectionHeaderView  = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XJTiXianSectionHeaderView"];
    [sectionHeaderView configureXJTixianSecitonHeaderWithTitle:self.sectionArr[section] section:section];
    
    
    XJWeakSelf(self);
    sectionHeaderView.clickTiXianManagerBlock = ^{
      //跳转账号管理界面
        XJWalletTiXianAccountViewController *accountVC = [[XJWalletTiXianAccountViewController alloc] init];
        [weakself.navigationController pushViewController:accountVC animated:YES];
    };
    return sectionHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //作用:实现单选效果
    if (indexPath.section == 1) {
        for (XJTiXianModel *model in self.accountArr) {
            model.check = NO;
        }
        XJTiXianModel *currentM = self.accountArr[indexPath.row];
        currentM.check = YES;
        //单刷新某一个section应该更合理。但是控制台会有一堆警告。
//        NSIndexSet *set = [NSIndexSet indexSetWithIndex:1];
//        [self.tableView reloadSections:set withRowAnimation:(UITableViewRowAnimationFade)];
        
        
        self.index = indexPath.row + 1; //标记选择的账户余额
        [self.tableView reloadData];
    }
}

#pragma mark - 四 请求数据
//获取提现账户数据接口
- (void)requestData {
    [XJHttpTool requestCustomAccountAccountListSuccessH:^(id responseObjc) {

        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            //账户余额
            self.balance = [NSString stringWithFormat:@"%@",responseObjc[@"data"][@"balance"]];
            
            NSArray *account_list = responseObjc[@"data"][@"account_list"];
            self.accountArr = [self reAssembleRequestData:account_list];
            
            //这个是提现用的
            self.tiXianArray = [self tixianJieKouYongDe:account_list];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}


//确认提现接口
- (void)requestTiXianWithDic:(NSDictionary *)parDic {
    
    [XJHttpTool requestCustomAccountTiXianWithParDic:parDic successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            [JRToast showWithText:@"未来巴扎:提现成功"];
        }else {
            [JRToast showWithText:[NSString stringWithFormat:@"未来巴扎:%@",responseObjc[@"message"]]];
        }
    } failH:^(NSError *error) {
       
        [JRToast showWithText:[error localizedDescription]];
    }];
}
#pragma mark - 五 Private method
/**重新组装服务器返回的数据*/
- (NSMutableArray *)reAssembleRequestData:(NSArray *)arr{
    
    NSMutableArray *newArr = [NSMutableArray array];
    for (NSDictionary *tempDic in arr) { // dic类型不一致
        
        NSMutableDictionary *newDic = @{}.mutableCopy;
        
        if ([[tempDic allKeys] containsObject:@"bank_branch"]) { //银行卡
            
            [newDic setValue:tempDic[@"type"] forKey:@"type"];
            [newDic setValue:tempDic[@"card_name"] forKey:@"name"];
            [newDic setValue:tempDic[@"card_number"] forKey:@"cardNum"];
            
        }else { //支付宝
            
            [newDic setValue:tempDic[@"type"] forKey:@"type"];
            [newDic setValue:tempDic[@"customer_name"] forKey:@"name"];
            [newDic setValue:tempDic[@"pay_name"] forKey:@"cardNum"];
            
        }

        //直接转model ,转完之后直接存数组中
        XJTiXianModel *model = [XJTiXianModel mj_objectWithKeyValues:newDic];
        
        [newArr addObject:model];
    }
    
    return newArr;
}

/**确认 提现接口用的*/
- (NSMutableArray *)tixianJieKouYongDe:(NSArray *)array {
    //是怎么写出这样的垃圾代码的的？
    //服务器返回一个数组(两个model还不一样) 每次的顺序也不一样。dic在数组中的位置也不一样。我又想转模型。我需要的只是将对应的dic转换为对应的model 。我能想到的是:判断dic中是否有对应的key 来找到对应的dic--->model
    
    NSMutableArray *newArr = [NSMutableArray array];
    
    for (NSDictionary * tempDic in array) {
        
        NSArray *allkeys = [tempDic allKeys];
        if ([allkeys containsObject:@"bank_branch"]) {
            //两个模型不一样
            XJWalletTiXianBankModel *bankM = [XJWalletTiXianBankModel mj_objectWithKeyValues:tempDic];
            
            [newArr addObject:bankM];
        }else {
            XJWalletTiXianZFBModel *zfbM = [XJWalletTiXianZFBModel mj_objectWithKeyValues:tempDic];
            [newArr addObject:zfbM];
        }
    }
    
    return newArr;
}
#pragma mark - 六 吐槽
// 1.产品也是个sb
// 2.服务器返回的数据也是呵呵呵. 为什么不返回类型一直到的数据?本来以为写完了。一调接口发现挂了。写的乱七八糟的。简单的东西非考疼你

#pragma mark - 六 服务器返回的数据
/**
 
 {
 "data" : {
 "balance" : 0,
 "account_list" : [
 {
 "bank_branch" : "亳州支行",
 "card_number" : "6217002710005555",
 "card_name" : "嘻嘻",
 "bank_name" : "工商银行",
 "id" : 104,
 "create_time" : 1530186742566,
 "type" : 1,
 "customer_id" : 7
 },
 {
 "pay_name" : "147852369",
 "id" : 108,
 "customer_name" : "Refer",
 "customer_id" : 7,
 "create_time" : 1530241899279,
 "type" : 0
 }
 ]
 },
 "code" : 0
 }
 

 */

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
